const {desktopCapturer} = require('electron');
/**
 * 截图模块
 * @fileoverview DesktopCapture class.
 */
module.exports = class DesktopCapture {

    /**
     * 截图
     * @param {Function} callback 回调函数，参数为base64编码的图片数据
     */
    static capture(callback) {
        desktopCapturer.getSources({types: ['window']}, (error, sources) => {
            console.log(sources);
            console.log(error);
            if (error) throw error;
            for (const source of sources) {
                console.log(source);
                if (source.name === 'Entire screen' || source.name === 'Screen 0') {
                    navigator.mediaDevices.getUserMedia({
                        audio: false,
                        video: {
                            mandatory: {
                                chromeMediaSource: 'desktop',
                                chromeMediaSourceId: source.id,
                                minWidth: 1280,
                                maxWidth: 4096,
                                minHeight: 720,
                                maxHeight: 4096
                            }
                        }
                    }).then(stream => {
                        const video = document.createElement('video');
                        video.srcObject = stream;
                        video.onloadedmetadata = () => {
                            video.play();
                        };
                        const canvas = document.createElement('canvas');
                        canvas.width = video.videoWidth;
                        canvas.height = video.videoHeight;
                        canvas.getContext('2d').drawImage(video, 0, 0);
                        callback(canvas.toDataURL('image/png'));
                        stream.getTracks().forEach(track => track.stop());
                    }).catch(error => console.log(error));
                    break;
                }
            }
        });
    }
    //截图页面
    static capturePage(mainWindow, callback) {
        const options = {
            format: 'png',
            quality: 100
        };
        mainWindow.webContents.capturePage(options, (image) => {
            callback(image.toDataURL());
        });
    }
}